﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.CM.CMBill.RcvBill;
    using UFIDA.U9.CM.CMBillBP;
    using UFSoft.UBF.AopFrame;	
	using UFSoft.UBF.Util.Context;

	/// <summary>
	/// CMRcvBillUnApproveSV partial 
	/// </summary>	
	public partial class CMRcvBillUnApproveSV 
	{	
		internal BaseStrategy Select()
		{
			return new CMRcvBillUnApproveSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class CMRcvBillUnApproveSVImpementStrategy : BaseStrategy
	{
		public CMRcvBillUnApproveSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			CMRcvBillUnApproveSV bpObj = (CMRcvBillUnApproveSV)obj;

			try
			{
				if (bpObj.Data == null || bpObj.Data.Count == 0)
					throw new Exception("传入参数为空");
				List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();

				foreach (var dto in bpObj.Data)
				{
					if (String.IsNullOrEmpty(dto.DocNo))
						throw new Exception("必须传入单号[DocNo]");

					CMRcvBill doc = CMRcvBill.Finder.Find($"DocNo='{dto.DocNo}'");
					if (doc == null)
					{
						//新增逻辑
						throw new Exception($"单号[{dto.DocNo}]不存在!");

					}
					else
					{
						//修改逻辑
						if (doc.DocStatus != UFIDA.U9.CBO.FI.Enums.BillStatusEnum.Approved)
							throw new Exception($"单号[{doc.DocNo}]状态不为已审,不能弃审");
						//审核
						doc = UnApproveDoc(doc);
						//返回值
						CommonArchiveDataDTOData ret = new CommonArchiveDataDTOData()
						{
							ID = doc.ID,
							Code = doc.DocNo,
						};
						retlist.Add(ret);
					}
				}

				return ResultUtils.success(bpObj, bpObj.Data, retlist);
			}
			catch (Exception ex)
			{
				return ResultUtils.error(bpObj, bpObj.Data, ex);
			}
		}

        private CMRcvBill UnApproveDoc(CMRcvBill doc)
        {
			CancelApproveBillBP approve = new CancelApproveBillBP();
			approve.BillID = doc.ID;
			approve.BusinessType = UFIDA.U9.Base.Doc.BusinessTypeEnum.CM_Pay;
			approve.CurrentSysVersion = doc.SysVersion;
			string ret = approve.Do();

			return doc;
		}
    }

	#endregion
	
	
}